<template>
  <div class="box">
    <div class="add">
      <a-button type="primary" @click="visible = true" block>添加</a-button>

      <br />
      <br />
      <a-button @click="fresh" block>刷新</a-button>
      <br />
      <br />
    </div>
    <br />
    <div class="content">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        bordered
      >
        <template
          v-for="col in ['url', 'phone', 'remake']"
          #[col]="{ text, record }"
          :key="col"
        >
          <div>
            <template v-if="editableData[record.id] && col == 'url'">
              <a-input
                v-if="editableData[record.id]"
                style="margin: -5px 0"
                v-model:value="editableData[editIndex[record.id]].url"
              />
            </template>
            <template v-else-if="editableData[record.id] && col == 'phone'">
              <!-- <a-input
              v-if="editableData[record.id]"
              style="margin: -5px 0"
              v-model:value="editableData[editIndex[record.id]].account_id"
            /> -->
              <a-textarea
                size="large"
                v-model:value="editableData[editIndex[record.id]].phone"
              />
            </template>
            <template v-else-if="editableData[record.id] && col == 'remake'">
              <a-input
                v-if="editableData[record.id]"
                style="margin: -5px 0"
                v-model:value="editableData[editIndex[record.id]].remake"
              />
            </template>

            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template #lastTime="{ record }"> {{ record.lastTime }} </template>
        <template #is_call="{ record }">
          <!-- v-model:checked="checked1" -->
          <a-switch
            checked-children="开"
            un-checked-children="关"
            v-model:checked="record.is_call"
            @change="is_call_change($event, record['id'])"
          />
        </template>
        <template #work_status="{ record }">
          <!-- v-model:checked="checked1" -->
          <!-- <a-switch checked-children="开" un-checked-children="关" /> -->

          <a-button type="danger" v-if="record.work_status == 0"
            >无法访问</a-button
          >
          <a-button v-else class="success">正常访问</a-button>
        </template>
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <a @click="save(record.id)">Save</a>
              <!-- 气泡 -->
              <a-divider type="vertical" />
              <a-popconfirm
                title="Sure to cancel?"
                @confirm="cancel(record.id)"
              >
                <a>Cancel</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.id)">Edit</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="Sure to delete?"
                @confirm="deleteDmp(record.id)"
              >
                <a>delete</a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal v-model:visible="visible" title="添加" @ok="handleOk">
      <template v-for="(item, index) in fromAdd" :key="item.label">
        <form-is
          ref="formIs"
          :valueArray="item"
          @test="(arg) => addSubmit(arg, index)"
        />
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts">
import {
  _checkUrlSum,
  _checkUrladd,
  _checkurlSelect,
  _checkurlUpdate,
  _checkUrldelete,
  _checkurlCheck,
} from "@/api/checkurl/index";
import { cloneDeep, forEach } from "lodash";
import formIs from "@/components/formIs.vue";
import { componentFrom, checkUrlDataItemAdd } from "@/type";
// import store from "@/store";
import { computed, defineComponent, reactive, ref, UnwrapRef } from "vue";
import { message } from "ant-design-vue/es";
import { is_phone, is_url } from "@/lib/is";
const columns = [
  {
    title: "url",
    dataIndex: "url",
    // width: "10%",
    slots: { customRender: "url" },
  },

  {
    title: "phone",
    dataIndex: "phone",
    idth: "10%",
    slots: { customRender: "phone" },
  },

  {
    title: "备注(操作人）",
    dataIndex: "remake",
    // width: "40%",
    slots: { customRender: "remake" },
  },
  {
    title: "work_status",
    dataIndex: "work_status",
    // width: "10%",
    slots: { customRender: "work_status" },
  },
  // {
  //   title: "状态",
  //   dataIndex: "work_status",
  //   // width: "40%",
  //   slots: { customRender: "address" },
  // },
  {
    title: "通知功能",
    dataIndex: "is_call",
    // width: "30%",
    slots: { customRender: "is_call" },
  },
  {
    title: "最后修改时间",
    dataIndex: "last_time",
    // width: "40%",
    // slots: { customRender: "lastTime" },
  },
  {
    title: "operation",
    dataIndex: "operation",
    slots: { customRender: "operation" },
  },
];

// 模拟请求
const data: checkUrlDataItemAdd[] = [];
const fromAddType: componentFrom[] = [
  {
    label: "url",
    value: "",
    type: "urlRequire",
    status: false,
  },
  {
    placeholer: "电话可以多个输入，换行即可",
    label: "phone",
    value: "",
    type: "phoneNumberRequire",
    inputType: "textarea",
    status: false,
  },
  {
    label: "remake",
    value: "",
    type: "require",
    status: false,
  },
];
interface editIndexInter {
  [index: number]: number;
}
export default defineComponent({
  components: {
    formIs,
  },
  setup() {
    //组件
    const formIs = ref();
    const editIndex = ref<editIndexInter>({});
    const fromAdd = fromAddType;
    const dataSource = ref(data);
    //dialog的浮窗
    const visible = ref<boolean>(false);
    const value = ref<string>("false");
    // const editableData = reactive<DMPDataItemAdd[]>([]);
    const editableData: UnwrapRef<checkUrlDataItemAdd[]> = reactive([]);
    let current = ref<number>(1);
    let pageSize = ref<number>(8);
    let total = ref<number>(0);
    const edit = (id: number) => {
      let tmp = cloneDeep(dataSource.value.filter((item) => id === item.id));
      editableData[id] = tmp[0];
      editIndex.value[id] = id;
    };
    const save = (key: number) => {
      let tmp = editableData[key];
      // tmp["work_status"] = false;
      // tmp["is_call"] = false;
      console.log(tmp);
      if (!is_url(tmp.url!)) {
        message.info("地址不为地址");
        return;
      }
      let phone = tmp.phone!;
      var arr = phone.split("\n");
      arr.map((item: string) => {
        if (!is_phone(item)) {
          message.info("要检查一下电话号码啊 ");
          return;
        }
      });
      _checkurlUpdate(tmp).then((res) => {
        _checkurlCheck().then(() => {
          current.value = 1;
          cancel(key);
        });
      });
    };
    const cancel = (key: number) => {
      delete editableData[key];
      delete editIndex.value[key];
      paginationAPi();
      //刷新当前页面
    };
    const deleteDmp = (key: number) => {
      _checkUrldelete({ id: key }).then((res) => {
        cancel(key);
      });
    };
    const handleOk = () => {
      let tmp = true;
      let object: any = {};
      fromAdd.map((item) => {
        object[item.label] = item.value;
        if (item.status == false) {
          message.info("<" + item.label + ">选项没填");
          tmp = false;
          return;
        }
      });
      if (!tmp) return;
      object["work_status"] = false;
      object["is_call"] = false;
      // formIs.value.ErrorString();
      console.log(object);
      _checkUrladd(object)
        .then((res) => {
          _checkurlCheck().then(() => {
            visible.value = false;
            current.value = 1;
            // paginationAPi();
            // 清空
            fromAdd.map((item: any) => {
              item.value = "";
              item.status = false;
            });
          });
        })
        .catch((e: any) => {
          console.log(e);
        });
    };
    const addSubmit = (e: boolean, index: number) => {
      fromAdd[index].status = e;
      // console.log(fromAdd[index]);
    };

    _checkurlCheck();

    const pagination = computed(() => ({
      total: total.value,
      current: current.value,
      pageSize: pageSize.value,
    }));
    const handleTableChange = (page: any, filters: never, sorter: never) => {
      // aas sadas/aa
      current.value = Number(page.current);
      paginationAPi();
    };

    const paginationAPi = () => {
      _checkUrlSum().then((res) => {
        console.log(res);
        console.log(Number(res.data.value) + "查询");
        total.value = Number(res.data.value);
      });
      _checkurlSelect(pagination.value).then((res) => {
        // console.log(rs)
        res.data.value.map((item: checkUrlDataItemAdd) => {
          item["is_call"] = item["is_call"] == "1" ? true : false;
          // console.log(item["is_call"]);
          // console.log(typeof item["is_call"]);
        });
        console.log(res.data.value);
        dataSource.value = res.data.value;
      });
    };
    const is_call_change = (item: any, id: number) => {
      let data = { id: id, is_call: item };
      console.log(data);
      _checkurlUpdate(data).then((res) => {
        console.log(data);
        // current.value = 1;
        // cancel(key);
      });
    };
    const fresh = () => {
      paginationAPi();
    };
    // 初始化
    _checkUrlSum()
      .then((res) => {
        console.log(res);
        total.value = Number(res.data.value);
        if (total.value != 0) {
          paginationAPi();
        }
      })
      .catch((e: any) => {
        console.log("ERROR:" + e);
      });
    // 初始化
    return {
      editIndex,
      current,
      pageSize,
      fromAdd,
      value,
      dataSource,
      columns,
      editingKey: "",
      editableData,
      visible,
      pagination,
      total,
      handleOk,
      edit,
      save,
      addSubmit,
      cancel,
      handleTableChange,
      deleteDmp,
      is_call_change,
      fresh,
    };
  },
});
</script>
<style lang="scss" scoped>
.success {
  border: 1px solid #2d7b2a !important;
  color: #2d7b2a !important;
}
.content {
  // overflow: auto;
}
.box {
  padding: 0 20px 0 20px;
}
.add {
  width: 100%;
}
.formItem {
  .formlabel {
    padding: 5px;
  }
  padding: 5px 0 5px 0;
}
</style>
